package com.gack.business.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.gack.business.model.Message;
import com.gack.business.model.User;
import com.gack.business.model.VideoCancelOrderformReason;
import com.gack.business.model.VideoOrderform;
import com.gack.business.model.VideoStores;
import com.gack.business.repository.MessageRepository;
import com.gack.business.repository.UserRepository;
import com.gack.business.repository.VideoCancelOrderformReasonRepository;
import com.gack.business.repository.VideoOrderformRepository;
import com.gack.business.repository.VideoStoresRepository;
import com.gack.helper.common.abstractobj.Result;
import com.gack.helper.common.util.SendCode;

/**
 * 
* @ClassName: VideoOrderformService.java 
* @Description: 评价controller
* @author Cancerl
* @date 2018年3月21日
*  
 */
@Service
public class VideoOrderformService implements VideoOrderformServiceInterface {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private VideoStoresRepository storesRepository;
	@Autowired
	private VideoOrderformRepository orderformRepository;
	@Autowired
	private VideoCancelOrderformReasonRepository cancelOrderformReasonRepository;
	@Autowired
	private MessageRepository messageRepository;
	
	/**
	 * 门店预约
	 * 用户id， 门店id
	 */
	@Override
	public Result reservateStore(String userid, String storeid,String operation) {
		Result result = new Result();
		User user = userRepository.findOne(userid);
		VideoStores store = storesRepository.findOne(storeid);
		if(user != null && store != null){
			//用户存在已预约订单信息，无法再次预约
			List<VideoOrderform> reservationOrderform = orderformRepository.findByUserAndOrderStatusIsNotAndOrderStatusIsNot(user, "2", "4");
			if(reservationOrderform != null && reservationOrderform.size() > 0){
				//用户已存在预约订单  无法再次预约
				result.setKey("error");
				result.setValue("用户已存在预约或使用中订单，无法再次预约");
			}else if( 2 == store.getStatus()){
				//店铺不可用 无法预约
				result.setKey("error");
				result.setValue("店铺已被他人预约，请重新选择店铺进行预约");
			}else{
				try {
					VideoOrderform orderform = new VideoOrderform();
					orderform.setUser(user);
					orderform.setStore(store);
					orderform.setOrderStatus("1");
					orderform.setPlaceOrdertime(new Date());
					String orderNumber = "GV"+(new Date()).getTime();//设置订单编号
					orderform.setOrderNumber(orderNumber);
					orderform = orderformRepository.save(orderform);
					//门店预约成功  改变门店状态
					store.setStatus(2);
					storesRepository.save(store);
					//预约成功   向门店管理者及用户发送短信
					SendCode.sendMessage(user.getUsername(), "您已成功预约，在订单开始使用前预约状态将会保留30分钟，预约保留时间到达后会自动取消预约订单，请准时到达");
					//sendCode.sendMessage(store.getStorePhone(), "有用户成功预约门店，请做好准备，确保门店设备正常使用");
					SendCode.sendMessage(store.getStorePhone(), "手机尾号为"+user.getUsername().substring(7)+"客户，已经预约您的门店进行办公，预计三十分钟内到达使用。");
					//返回的订单中店铺状态为3
					orderform.getStore().setStatus(3);
//					Map<String, Object> orderMap = new HashMap<>();
//					orderMap.put("orderform", orderform);
//					orderMap.put("nowDate", new Date());
//					result.setKey("success");
					//result.setValue("门店预约成功");
//					result.setValue(orderform);	//预定成功 返回订单信息
//					result.setValue(orderMap);
					if(operation.equals("android")){
						result.setKey("success");
						result.setValue(orderform.getId());
					}else{
						result.setKey("success");
						result.setValue(orderform);
					}
				} catch (Exception e) {
					e.printStackTrace();
					result.setKey("error");
					result.setValue("短信发送失败");
				}
			}
		}else{
			result.setKey("error");
			result.setValue("用户/门店不存在，无法创建订单，预约失败");
		}
		return result;
	}

	/**
	 * 取消预约
	 * 根据用户id 查询订单  取消订单预约
	 */
	@Override
	public Result cancelReservation(String id,String reason) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatus(user, "1");
			if(orderforms != null && orderforms.size() > 0){
				VideoOrderform orderform = orderforms.get(0);
				if(orderform != null){
					try{
						//订单取消  改变订单状态   设置结束时间，此时订单结束时间代表订单关闭时间 （订单取消既订单关闭）
						orderform.setOrderStatus("2");
						orderform.setOrderEndtime(new Date());
						orderform = orderformRepository.save(orderform);
						//门店订单取消  改变门店状态为未预定
						VideoStores store = orderform.getStore();
						if(store != null){
							store.setStatus(1);
							storesRepository.save(store);
						}
						//添加取消原因
						//如果不存在取消预约订单信息  添加取消预约
						List<VideoCancelOrderformReason> cancelOrderformReasons = cancelOrderformReasonRepository.findByOrderform(orderform);
						if( cancelOrderformReasons == null || cancelOrderformReasons.size() == 0){
							VideoCancelOrderformReason cancelOrderformReason = new VideoCancelOrderformReason();
							cancelOrderformReason.setReason(reason);
							cancelOrderformReason.setOrderform(orderform);
							cancelOrderformReasonRepository.save(cancelOrderformReason);
						}
						//orderform.setCancelReason(cancelOrderformReason);
						//orderform = orderformRepository.save(orderform);
						//用户取消订单后添加用户message信息
						Message message = new Message();
						message.setMessage("您预约的会议室（"+orderform.getStore().getStoreName()+"）已取消");
						message.setType("预约消息");
						message.setMesType(0);
						message.setSendWay(2);
//						message.setUser(orderform.getUser());
						message.setUserid(orderform.getUser().getId());
						message.setCreatetime(new Date());
						messageRepository.save(message);
						
						//短信通知店铺管理者及用户
						SendCode.sendMessage(orderform.getUser().getUsername(), "您已成功取消店铺预约");
						//sendCode.sendMessage(orderform.getStore().getStorePhone(), "已有用户取消店铺预约");
						SendCode.sendMessage(orderform.getStore().getStorePhone(), "手机尾号为"+user.getUsername().substring(7)+"客户，已经取消预约您的门店进行办公。");
						result.setKey("success");
						result.setValue("订单取消成功");
					}catch (Exception e) {
						e.printStackTrace();
						result.setKey("error");
						result.setValue("取消订单操作失败");
					}
				}else{
					result.setKey("error");
					result.setValue("未找到该订单，取消订单操作失败");
				}
			}else{
				result.setKey("error");
				result.setValue("该用户不存在预约订单，取消订单预约失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，取消订单操作失败");
		}
		return result;
	}

	/**
	 * 开始使用订单
	 */
	@Override
	public Result startToUseOrderform(String id) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			//订单仅预约状态可开始
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatus(user, "1");
			List<VideoOrderform> orderforms_usered = orderformRepository.findByUserAndOrderStatus(user, "3");
			if(orderforms != null && orderforms.size() > 0){
				VideoOrderform orderform = orderforms.get(0);
				try{
					//订单开始使用    重新设置订单开始使用时间，设置订单状态  返回订单信息（包含店铺信息,以便展示）
					orderform.setPlaceOrdertime(new Date());
					orderform.setOrderStatus("3");
					orderformRepository.save(orderform);
					//使用中 返回店铺状态  4
					orderform.getStore().setStatus(4);
//					Map<String, Object> orderMap = new HashMap<>();
//					orderMap.put("orderform", orderform);
//					orderMap.put("nowDate", new Date());
					result.setKey("success");
					result.setValue(orderform);
//					result.setValue(orderMap);
				}catch (Exception e) {
					e.printStackTrace();
					result.setKey("error");
					result.setValue("订单开始使用操作失败");
				}
			}else if(orderforms_usered != null && orderforms_usered.size() > 0){
				//存在使用中订单  无法再次开始使用
				result.setKey("success");
				result.setValue("订单已开始使用");
			}else{
				result.setKey("error");
				result.setValue("用户不存在预约订单，订单开始使用失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，订单开始使用失败");
		}
		return result;
	}

	/**
	 * 结束使用订单
	 */
	@Override
	public Result endToUseOrderform(String id) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatus(user, "3");
			if(orderforms != null && orderforms.size() > 0){
				VideoOrderform orderform = orderforms.get(0);
				try{
					//订单停止使用    设置订单结束时间，设置订单状态  返回订单信息（包含店铺信息,以便展示）
					orderform.setOrderEndtime(new Date());
					orderform.setOrderStatus("4");
					orderformRepository.save(orderform);
					//门店订单完成  更改门店状态   门店可预订
					VideoStores store = orderform.getStore();
					if(store != null){
						store.setStatus(1);
						storesRepository.save(store);
					}
					result.setKey("success");
					result.setValue(orderform);
				}catch (Exception e) {
					e.printStackTrace();
					result.setKey("error");
					result.setValue("订单开始使用操作失败");
				}
			}else{
				result.setKey("error");
				result.setValue("用户不存在使用中订单，订单结束使用操作失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，结束使用订单失败");
		}
		return result;
	}

	/**
	 * 查询所有订单信息（不包括以取消订单信息）
	 * 订单信息  按照place_ordertime 倒叙排列 （由于预约的订单结束时间为空）
	 */
	@Override
	public Result findAllOrderform(String id, Integer currentPage, Integer pageSize) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			try{
				Sort sort = new Sort(Sort.Direction.DESC, "placeOrdertime");
				Pageable pageable = new PageRequest(currentPage, pageSize, sort);
				Page<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatusIsNot(user, "2", pageable);
				result.setKey("success");
				result.setValue(orderforms);
			}catch (Exception e) {
				e.printStackTrace();
				result.setKey("error");
				result.setValue("订单查询操作失败");
			}
		}else{
			result.setKey("error");
			result.setValue("用户不存在，订单查询失败");
		}
		return result;
	}

	/**
	 * 根据订单id查询订单详情
	 */
	@Override
	public Result findOrderformInfo(String id) {
		Result result = new Result();
		/*VideoOrderform orderform = orderformRepository.findOne(id);
		if(orderform != null){
			//订单状态为已预定，设置店铺状态为3
			//订单状态为使用中，设置店铺状态为4
			if("1".equals(orderform.getOrderStatus())){
				orderform.getStore().setStatus(3);
			}else if("3".equals(orderform.getOrderStatus())){
				orderform.getStore().setStatus(4);
			}
			result.setKey("success");
			result.setValue(orderform);
		}else{
			result.setKey("error");
			result.setValue("该订单不存在");
		}*/
		return result;
	}

	/**
	 * 根据用户id查询用户使用中或者预定中的订单
	 */
	@Override
	public Result findOrderformInfoByUserId(String id) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatusIsNotAndOrderStatusIsNot(user, "2", "4");
			if(orderforms != null && orderforms.size() > 0){
				VideoOrderform orderform = orderforms.get(0);
				if(orderform != null){
					//查询出可用订单详情，返回
					Map<String, Object> orderMap = new HashMap<>();
//					orderMap.put("orderform", orderform);
//					orderMap.put("nowDate", new Date());
					result.setKey("success");
					result.setValue(orderform);
//					result.setValue(orderMap);
				}
			}else{
				result.setKey("error");
				result.setValue("用户不存在预约或使用中订单，订单详情查询失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，订单详情查询失败");
		}
		return result;
	}

	/**
	 * 通过用户id开始使用订单
	 */
	@Override
	public Result startToUseOrderformByUserid(String id) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			//查询用户预订状态订单  只用用户存在已预约订单 才会允许 执行开始订单操作  修改订单状态
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatus(user, "1");
			if(orderforms != null && orderforms.size() > 0){
				try{
					VideoOrderform orderform = orderforms.get(0);
					//订单开始使用    重新设置订单开始使用时间，设置订单状态  返回订单信息（包含店铺信息,以便展示）
					orderform.setPlaceOrdertime(new Date());
					orderform.setOrderStatus("3");
					orderformRepository.save(orderform);
					result.setKey("success");
					result.setValue(orderform);
				}catch (Exception e) {
					e.printStackTrace();
					result.setKey("error");
					result.setValue("订单开始使用操作失败");
				}
			}else{
				result.setKey("error");
				result.setValue("该用户不存在已预订订单，订单开始操作失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，开始使用操作失败");
		}
		return result;
	}

	/**
	 * 通过用户id结束使用订单
	 */
	@Override
	public Result endToUseOrderformByUserid(String id) {
		Result result = new Result();
		User user = userRepository.findOne(id);
		if(user != null){
			List<VideoOrderform> orderforms = orderformRepository.findByUserAndOrderStatus(user, "3");
			if(orderforms != null && orderforms.size() > 0){
				try{
					// 店铺存在状态  ， 1预定  2已预订或已使用   无法预定
					// 结束订单后需要回复店铺的可使用状态
					VideoOrderform orderform = orderforms.get(0);
					//订单停止使用    设置订单结束时间，设置订单状态  返回订单信息（包含店铺信息,以便展示）
					orderform.setOrderEndtime(new Date());
					orderform.setOrderStatus("4");
					orderformRepository.save(orderform);
					//门店订单完成  更改门店状态   门店可预订
					VideoStores store = orderform.getStore();
					if(store != null){
						store.setStatus(1);
						storesRepository.save(store);
					}
					result.setKey("success");
					result.setValue(orderform);
				}catch (Exception e) {
					e.printStackTrace();
					//订单操作执行异常
					result.setKey("error");
					result.setValue("订单结束使用操作失败");
				}
			}else{
				result.setKey("error");
				result.setValue("该用户不存在使用中的订单，结束订单操作失败");
			}
		}else{
			result.setKey("error");
			result.setValue("该用户不存在，结束订单操作失败");
		}
		return result;
	}

}
